/*
** $Id: crypter_des_cfb.c 10 2014-08-24 13:20:16Z chupin007@gmail.com $
** $HeadURL: http://bapps.googlecode.com/svn/trunk/src/enc/src/crypter_des_cfb.c $
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <openssl/des.h>

DES_cblock       Key2, Key3;
DES_key_schedule schedule;

char Key[9];

void crypterInit( int command, char *key ) {

  if( strlen( key ) < 8 ) {
    fprintf( stderr, "wronng key:len=%d, %s\n", strlen( key ), key );
    exit( 1 );
  }
  memcpy( Key, key, 8 );
  Key[8] = '\0';

  memcpy( Key2, Key, 8 );
  DES_set_odd_parity( &Key2 );
  DES_set_key_checked( &Key2, &schedule );
  memcpy( Key3, Key2, sizeof( Key2 ) );

}

int crypterEncrypt( int nfld, char *buff, char *crypted, int len ) {
  int ncrypted=0;
  memcpy( Key2, Key3, sizeof( Key3 ) );
  DES_cfb64_encrypt( ( unsigned char * ) buff, ( unsigned char * ) crypted, len, &schedule, &Key2, &ncrypted, DES_ENCRYPT );
  return len;

}

int crypterDecrypt( int nfld, char *crypted, char *buff, int len ) {
  int ncrypted=0;
  memcpy( Key2, Key3, sizeof( Key3 ) );
  DES_cfb64_encrypt( ( unsigned char * ) crypted, ( unsigned char * ) buff, len, &schedule, &Key2, &ncrypted, DES_DECRYPT );
  buff[len] = '\0';
  return len;

}
